package com.openlab.service.pet.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.openlab.common.utils.Result;
import com.openlab.service.pet.entity.CommunityInfo;
import com.openlab.service.pet.entity.Pet;
import com.openlab.service.pet.entity.PetVaccinate;
import com.openlab.service.pet.entity.WechatMpUser;
import com.openlab.service.pet.service.CommunityInfoService;
import com.openlab.service.pet.service.PetService;
import com.openlab.service.pet.service.PetVaccinateService;
import com.openlab.service.pet.service.WechatMpUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private PetService petService;

    @Autowired
    private PetVaccinateService petVaccinateService;

    @Autowired
    private CommunityInfoService communityInfoService;
    @Autowired
    private WechatMpUserService wechatMpUserService;


    @PostMapping("list")
    public Result getAllPet(@RequestBody HashMap<String,Object> hashMap){


        QueryWrapper<Pet> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name", "pet_type", "sex", "breed", "coat_color", "pet_license", "remove", "created_at");

        String breed=(String)hashMap.get("breed");
        String coatColor=(String) hashMap.get("coat_color");


        if ( hashMap.get("remove")!=null){
            Object remove= hashMap.get("remove");//注销
            queryWrapper.eq("remove",remove);
        }
        if ( hashMap.get("sex")!=null){
            Object  sex= hashMap.get("sex");//雌雄
            queryWrapper.eq("sex",sex);
        }
        if ( hashMap.get("license")!=null){
            Object license= hashMap.get("license");//登记
            if ((boolean)license)
            queryWrapper.gt("pet_license",0);//登记
            else
                queryWrapper.lt("pet_license",0);//登记

        }

        if (breed!=null)
        queryWrapper.eq("breed",breed);//品种
        if (coatColor!=null){

            queryWrapper.like("coat_color",coatColor);//毛色
        }



        //定义分页规则
        Integer pageNum=(Integer)hashMap.get("page_num");//页码
        Integer pageSize=(Integer)hashMap.get("page_size");//每页多少数据
        IPage<Pet> page = new Page<>(pageNum,pageSize);

        IPage<Pet> iPage = petService.page(page, queryWrapper);
        //page装换位list
        List<Pet> records = iPage.getRecords();

        records.forEach(System.out::println);
//        petService.page(page, queryWrapper);
//        后端返回数据
//                list,
//                total: res.total,
//                page_amount: Math.ceil(res.total / page_size),
//                page_num,
//                page_size
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", records);
        result.put("total",petService.count());
        result.put("page_amount",page.getPages());
        result.put("page_num",pageNum);
        result.put("page_size",pageSize);

        return Result.ok(200,result);
    }

//    id: this.$route.params.id,
//    community_id: this.postInfo.default_community_id
    @PostMapping("/detail")
    public Result getById(@RequestBody HashMap<String,Object> hashMap){

        HashMap<String, Object> result = new HashMap<>();

//       "name", "pet_type", "breed", "coat_color", "pet_license", "remove","photo"

        Object id = hashMap.get("id");
        Object communityId = hashMap.get("community_id");

        Pet pet = petService.getById((String)id);
        CommunityInfo communityInfo = communityInfoService.getById((Integer)communityId);

        result.put("name",pet.getName());
        result.put("pet_type",pet.getPetType());
        result.put("breed",pet.getBreed());
        result.put("coat_color",pet.getCoatColor());
        result.put("pet_license",pet.getPetLicenseAwardAt());
        result.put( "remove",pet.getRemove());
        result.put("photo",pet.getPhoto());
        result.put("wechat_mp_user_id",pet.getWechatMpUserId());
        result.put("community_name",communityInfo.getName());

        //vaccinates
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("vaccinated_at","vaccine_type");
        queryWrapper.eq("pet_id",id);
        List list = petVaccinateService.list(queryWrapper);

        Integer userId = pet.getWechatMpUserId();

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("id",userId);
        WechatMpUser one = wechatMpUserService.getOne(queryWrapper1);

        result.put("real_name",one.getRealName());
        result.put("vaccinates",list);



        return Result.ok(200,result);
    }

    @PostMapping("/license/{id}")
    public Result ChangeLicense(@PathVariable Integer id,@RequestBody HashMap hashMap){

        Object license = hashMap.get("pet_license");
        Object petLicenseAwardAt = hashMap.get("pet_license_award_at");
        UpdateWrapper<Pet> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set("pet_license",license);
        updateWrapper.set("pet_license_award_at",petLicenseAwardAt);
        petService.update(updateWrapper);
        HashMap<String, Object> result = new HashMap<>();
        result.put("pet_license",license);
        result.put("pet_license_award_at",petLicenseAwardAt);


        return Result.ok(200,result);
    }
    @PostMapping("/vaccinate/{id}")
    public Result addVaccinate(@PathVariable Integer id,@RequestBody HashMap hashMap){

//        private Integer id;
//        private Integer petId;
//        private Integer vaccinatedAt;
//        private Integer vaccinateType;
//        private Long createdAt;
        PetVaccinate petVaccinate = new PetVaccinate();

        Object vaccinatedAt = hashMap.get("vaccinated_at");
        Object vaccinateType = hashMap.get("vaccine_type");

        petVaccinate.setPetId(id);
        petVaccinate.setId(null);
        petVaccinate.setVaccinatedAt((Long) vaccinatedAt);
        petVaccinate.setVaccineType((String)vaccinateType );

        petVaccinate.setCreatedAt(0L);

        petVaccinateService.save(petVaccinate);

        HashMap<String, Object> result = new HashMap<>();
        result.put("vaccinated_at",vaccinatedAt);
        result.put("vaccinate_type",vaccinateType);

        return Result.ok(200,result);
    }
    @PostMapping("/option/ower")
    public Result testPhone(@RequestBody HashMap hashMap){
        Object p = hashMap.get("phone");
        QueryWrapper<WechatMpUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",p);
        WechatMpUser one = wechatMpUserService.getOne(queryWrapper);
        if (one==null) return Result.error();

        HashMap<String, Object> map = new HashMap<>();
        map.put("id",one.getId());
        map.put("real_name",one.getRealName());
        return Result.ok(200,map);
    }


    @PostMapping("/create")
    public Result createOnePet(@RequestBody HashMap hashMap){

        Object breed = hashMap.get("breed");
        Object coat_color = hashMap.get("coat_color");
        Object community_id = hashMap.get("community_id");
        Object haveLicense = hashMap.get("haveLicense");
        Object name = hashMap.get("name");
        Object pet_type = hashMap.get("pet_type");
        Object petLicense = hashMap.get("pet_license");
        Object petLicenseAwardAt = hashMap.get("pet_license_award_at");
        Object petType = hashMap.get("pet_type");
        Object photo = hashMap.get("photo");
        Object sex = hashMap.get("sex");
        Object vaccinatedAt = hashMap.get("vaccinated_at");
        Object userId = hashMap.get("user_id");
        Object vaccineType = hashMap.get("vaccine_type");

        Pet pet = Pet.builder().id(null)
                .wechatMpUserId((Integer) userId)
                .communityId((Integer) community_id)
                .petType(pet_type.equals("狗")?1:2)
                .name((String) name)
                .sex((Integer) sex)
                .photo("")
                .coatColor((String) coat_color)
                .breed((String) breed)
                .petLicense( (String)petLicense)
                .petLicenseAwardAt((Long) petLicenseAwardAt)
                .remove(0)
                .removeReason(null)
                .removedAt(null)
                .createdAt(0L).build();
        petService.save(pet);



        if ((boolean)haveLicense){

            PetVaccinate petVaccinate = PetVaccinate.builder().id(null).petId(pet.getId()).vaccinatedAt((Long) vaccinatedAt)
                    .vaccineType((String) vaccineType).createdAt(0L).build();
            petVaccinateService.save(petVaccinate);
        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("id",pet.getId());

        return Result.ok(200,result);
    }
}
